package se.webbzon.boltzmann.game.sequence.builder.dialogue;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import se.webbzon.boltzmann.game.object.dialogue.layout.ChoiceDialogueLayout;
import se.webbzon.boltzmann.game.object.dialogue.layout.DialogueLayout;
import se.webbzon.boltzmann.game.sequence.builder.SequenceBuilder;
import se.webbzon.oschi01.friendly.Friendly;

public class ChoiceDialogueRowDeflation extends AbstractDialogueRowDeflation {
	
	private final List<String> choices;

	/*============================================================
	Constructors
	============================================================*/
	
	public ChoiceDialogueRowDeflation() {
		choices = new ArrayList<String>();
	}
	
	public ChoiceDialogueRowDeflation(ChoiceDialogueRow row) {
		super(row);
		choices = new ArrayList<String>();
		for (int i = 0; i < row.choices(); i ++)
			choices.add(row.getChoice(i));
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public void inflate(ByteBuffer buff) {
		super.inflate(buff);
		
		short choices = buff.getShort();
		for (short i = 0; i < choices; i++) {
			byte[] data = new byte[buff.getShort()];
			buff.get(data, 0, data.length);
			try {
				this.choices.add(new String(data,"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				this.choices.add("");
			}
		}
	}

	@Override public ByteBuffer deflate(int allocate) {
		// Convert the text of the choices
		List<byte[]> choiceData = new ArrayList<byte[]>();
		int size = 2 + 2 * choices.size();
		for (String choice : choices) {
			byte[] data;
			try {
				data = choice.getBytes("UTF-8");
				size += data.length;
				choiceData.add(data);
			} catch (UnsupportedEncodingException e) {
				choiceData.add(new byte[0]);
			}
		}
		
		// Write to the buffer
		ByteBuffer buff = super.deflate(size);
		
		buff.putShort((short) choiceData.size());
		for (byte[] data : choiceData) {
			buff.putShort((short) data.length);
			buff.put(data);
		}
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/

	@Override @Friendly AbstractDialogueRow makeRow(SequenceBuilder builder,
													DialogueLayout layout) {
		ChoiceDialogueRow row = 
				new ChoiceDialogueRow	(builder,
										(ChoiceDialogueLayout) layout,
										getBackground(),
										getText());
		for (String choice : choices)
			row.addChoice(choice);
		return row;
	}
	
}
